package sgi.server;

import java.util.ArrayList;
import java.util.Date;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import sgi.message.*;
import ocsf.server.*;

public class SGIServer extends AbstractServer {
	  /**
	   * The default port to listen on.
	   */
	  final public static int DEFAULT_PORT = 5555;
	  private Connection connDB;
	  private SGIServerUI serverUI;
	  
	  public SGIServer(SGIServerUI serverUI)
	  {
		  super();
		  this.serverUI = serverUI;
		  serverUI.setVisible(true);
	  }
	 
	  public void initDBConnection(String dbName,String user, String pass) throws Exception
	  {
		  try 
			{
	            Class.forName("com.mysql.jdbc.Driver").newInstance();
	            connDB = DriverManager.getConnection("jdbc:mysql://109.186.62.7/"+dbName, user, pass);
	        } catch (Exception ex) {throw ex;}
	  }
	  
	  @SuppressWarnings("deprecation")
	public void handleMessageFromClient
	    (Object msg, ConnectionToClient client)
	  {
			try 
			{
				Statement stmt = connDB.createStatement();
							if(msg instanceof MessageLogin)
							{
								ResultSet rs = stmt.executeQuery(((Message)msg).getQuery());
								rs.next();
						/*Check if user details*/	
								if((rs.getString(1)).compareTo("1") == 0)
								{
						/*Set userOnline status to valid*/			
									stmt.executeUpdate("update users set userOnline='1' where username = '" + ((MessageLogin)msg).getUsername() + "' AND password = '" + ((MessageLogin)msg).getPassword() + "'");
									((MessageLogin)msg).setLoginSucceeded(true);
						/*Get privilege level*/
									rs = stmt.executeQuery("select privilege from users where username = '" + ((MessageLogin)msg).getUsername() + "' AND password = '" + ((MessageLogin)msg).getPassword() + "'");
									rs.next();
									((MessageLogin)msg).setPrivilege(Integer.valueOf(rs.getString(1)));
						/*Return message to client*/			
									client.sendToClient(msg);
									serverUI.display(((MessageLogin)msg).getUsername() + " logged in");
								}
								else
								{
									((MessageLogin)msg).setLoginSucceeded(false);
									((MessageLogin)msg).setLoginFailedMessage("Logging in failed");
									client.sendToClient(msg);
									serverUI.display(((MessageLogin)msg).getUsername() + "-logging in failed.");
								}
								rs.close();
							}

						else if(msg instanceof MessageLogoff)
						{
							stmt.executeUpdate("update users set userOnline='0' where username = '" + ((MessageLogoff)msg).getUsername() +  "' AND password = '" + ((MessageLogoff)msg).getPassword() + "'");
						}
						else if(msg instanceof MessagePrompt)
						{	
							serverUI.display(((MessagePrompt)msg).getQuery());
							
						}
						else if(msg instanceof MessageRegister)
						{
							/*Execute query to check if username already exists*/
							ResultSet rs = stmt.executeQuery("select COUNT(*) from users where username = '"+((MessageRegister)msg).getUsername()+"'");
							rs.next();
							if((rs.getString(1)).compareTo("1") == 0)
							{
								((MessageRegister)msg).setStatus(false);
								((MessageRegister)msg).setNotif("Username " + ((MessageRegister)msg).getUsername() + " already exists.");
							}
							else
							{
								stmt.executeUpdate(((MessageRegister)msg).getQuery());
								stmt.executeUpdate(((MessageRegister)msg).getQcustomer());
								((MessageRegister)msg).setStatus(true);
								((MessageRegister)msg).setNotif("New customer created");
								serverUI.display("Customer "+((MessageRegister)msg).getUsername() + " created.");
							}
							client.sendToClient(msg);	
						}
						else if(msg instanceof MessageComplaint)
						{
							stmt.executeUpdate(((MessageComplaint)msg).getQuery());
							((MessageComplaint)msg).setReceived(true);
							 Date date = new Date();
							 stmt.executeUpdate("update complaint set datetime = '"+(((int)date.getYear()+1900))+"-"+(((int)date.getMonth()+1))+"-"+(((int)date.getDay()+1))+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()+"' where datetime='0000-00-00 00:00:00'");
							serverUI.display("Customer "+((MessageComplaint)msg).getUsername() + " filed a complaint.");
							client.sendToClient(msg);
						}
						else if(msg instanceof MessageSearch)
						{
							
							ResultSet rs = stmt.executeQuery(((MessageSearch)msg).getQuery());
							
							if(rs.next() == false)
								((MessageSearch)msg).setImages(null);
							else
							{
								((MessageSearch)msg).setImages(new ArrayList<Integer>());
								do {
									((MessageSearch)msg).getImages().add(Integer.valueOf(rs.getString(1)));
								} while (rs.next());
							}						
							client.sendToClient(msg);
							serverUI.display("Search completed.");
						}
						else
						{
							serverUI.display("Unknow type of message Received");
						}
				
			} catch (Exception e) {e.printStackTrace();}
	  }

}
